// Copyright 2021 by 马万里. All rights reserved.
// 开发团队 ：   鸡中之霸
// 开发人员 ：   马万里
// 开发时间 ：   2021/3/3 10:43
// 文件名称 ：   user.go
// 工程名称 ：   seckill
// 开发工具 ：   GoLand
//

package controllers

import (
	"foreground/datamodels"
	"foreground/encrypt"
	"foreground/services"
	"foreground/tool"
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/mvc"
	"strconv"
)

type UserController struct {
	Ctx     iris.Context
	Service services.IUserService
}

func (u *UserController) GetRegister() *mvc.View {
	return &mvc.View{
		Name: "user/register.html",
	}
}

func (u *UserController) PostRegister() {
	var (
		nickName = u.Ctx.FormValue("nickName")
		userName = u.Ctx.FormValue("userName")
		password = u.Ctx.FormValue("password")
	)
	// ozzo-validation
	// github地址：
	//https://github.com/dchest/captcha
	//
	//文档地址：
	//https://godoc.org/github.com/dchest/captcha
	//
	//获取：
	//go get github.com/dchest/captcha
	user := &datamodels.User{
		NickName:     nickName,
		UserName:     userName,
		HashPassword: password,
	}

	_, err := u.Service.AddUser(user)
	if err != nil {
		u.Ctx.Redirect("/user/error")
		return
	}
	u.Ctx.Redirect("/user/login")
}

func (u *UserController) GetLogin() *mvc.View {
	return &mvc.View{
		Name: "user/login.html",
	}
}

func (u *UserController) PostLogin() mvc.Response {
	var (
		userName = u.Ctx.FormValue("userName")
		password = u.Ctx.FormValue("password")
	)
	user, ok := u.Service.IsPwdSuccess(userName, password)
	if !ok {
		return mvc.Response{
			Path: "/user/login",
		}
	}
	tool.GlobalCookie(u.Ctx, "uid", strconv.FormatInt(user.ID, 10))
	uidByte := []byte(strconv.FormatInt(user.ID, 10))
	uidString, err := encrypt.EnPwdCode(uidByte)
	if err != nil {
		u.Ctx.Application().Logger().Debug(err)
	}
	tool.GlobalCookie(u.Ctx, "sign", uidString)
	//u.Session.Set("userID",  strconv.FormatInt(user.ID, 10))
	return mvc.Response{
		Path: "/product/",
	}
}
